package com.fengycx.autoconfigure;

import com.fengycx.properties.GeoProperties;
import com.fengycx.temlate.RedisGeoTemplate;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
@EnableConfigurationProperties({GeoProperties.class})
public class RedisAutoConfiguration {

    @Bean
    public RedissonClient redissonClient(RedisProperties redisProperties){
        Config config = new Config();
        config.useSingleServer().setAddress("redis://"+redisProperties.getHost()+":"+redisProperties.getPort()).setPassword(redisProperties.getPassword());
        return Redisson.create(config);
    }

    @Bean
    public RedisGeoTemplate redisGeoTemplates(RedisTemplate redisTemplate, GeoProperties geoProperties){
        return new RedisGeoTemplate(redisTemplate,geoProperties);
    }


    /**
     * @Description: 自定义RedisTemplate对象注入Bean容器中,对默认模板进行改造后，基本支持所有数据类型
     * @Author: Neuronet
     * @Date: 2023/10/22 18:49
     **/
    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory factory) {
        // 1.创建一个RedisTemplate对象
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
        // 2.指定Redis连接工厂
        redisTemplate.setConnectionFactory(factory);
        // 3.创建一个JSON格式序列化对象，此处使用的是Redis自己的的序列化器
        GenericJackson2JsonRedisSerializer serializer = new GenericJackson2JsonRedisSerializer();
        // 4.指定除开hash数据类型之外的数据key和value使用什么序列化器
        redisTemplate.setKeySerializer(serializer);
        redisTemplate.setValueSerializer(serializer);
        // 5.指定hash数据类型的key和value序列化器
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(serializer);
        return redisTemplate;
    }
}
